<template>
    <view class="page over-auto-y column">
        <hj-navbar title="个人中心" :isShowBack="false" />
        <!-- 内容区 -->
        <view class="flex-auto w100 over-hide">
            <scroll-view
                scroll-y="true"
                class="big"
                :refresher-enabled="true"
                :refresher-triggered="triggered"
                @refresherrefresh="onRefresh"
            >
                <view class="pr-30 pl-30">
                    <UserInfo @init="getRorderTotal" />
                    <UserOrder :orderCount="orderCount" @init="getRorderTotal" />
                    <MyMenu @init="getRorderTotal" />
                    <HotelInfo />
                </view>
            </scroll-view>
        </view>
        <hj-footer-tabs :selectId="9" />
    </view>
</template>

<script setup>
/**
 * @description 小程序的个人中心
 * @author yinzhi
 * @date 2025-05
 */
import { onShow } from '@dcloudio/uni-app'
import { ref, defineComponent, computed } from 'vue'
import UserInfo from './components/UserInfo.vue'
import MyMenu from './components/MyMenu.vue'
import UserOrder from './components/UserOrder.vue'
import HotelInfo from './components/HotelInfo.vue'
import { logger } from '@/utils/log.js'
import { getOrderCountApi } from '@/libs/api/orderApi.js'
// 引入组件
defineComponent({
    components: {
        UserInfo,
        MyMenu,
        UserOrder,
        HotelInfo
    }
})

import { useStore } from 'vuex'
const store = useStore()
const token = computed(() => store.state.auth.token || '')

const triggered = ref(false)
const _freshing = ref(false)

const orderCount = ref({
    checkedInNum: 0,
    stayPayNum: 0,
    waitCheckInNum: 0
})

// 页面每次打开的时候都触发，除订单数据外，其他接口尽量放在需要时调用
onShow(() => {
    getRorderTotal()
})

// 获取订单统计数据
const getRorderTotal = async () => {
    if (!token.value) return
    try {
        const data = await getOrderCountApi()
        orderCount.value = data
    } catch (error) {
        logger.error('[getRorderTotal] 获取订单统计数据失败:', error)
    }
}

// 下拉刷新
const onRefresh = async () => {
    // 防止多次刷新
    if (_freshing.value) return
    _freshing.value = true
    triggered.value = true
    let time = setTimeout(() => {
        getRefresh()
        clearTimeout(time)
    }, 600)
}
// 刷新事件 等所有接口请求 完成后使刷新动画回弹
const getRefresh = () => {
    Promise.all([getRorderTotal()])
        .then(() => {
            triggered.value = false
            _freshing.value = false
        })
        .catch(() => {
            triggered.value = false
            _freshing.value = false
        })
}
</script>

<style scoped lang="scss">
.page {
    background: $uni-bg-color-grey;
}
</style>
